// components/blog-ctrl/blog-ctrl.js
let userInfo = {};
const db = wx.cloud.database();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog:Object
  },
  externalClasses: ["iconfont", 'icon-pinglun', 'icon-fenxiang'],
  /**
   * 组件的初始数据
   */
  data: {
    //登录组件
    loginShow: false,
    //底部弹出侧
    modalShow: false,
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment() {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: (res) => {
                userInfo = res.userInfo;
                //评论弹出层
                this.setData({
                  modalShow: true
                })
              }
            })
          } else {
            this.setData({
              loginShow: true
            })
          }
        }
      })
    },
    loginsuccess(event) {
      userInfo = event.detail;
      this.setData({
        loginShow: false
      }, () => {
        this.setData({
          modalShow: true
        })
      })


    },
    loginfail() {
      wx.showModal({
        title: '用户必须授权登录后才可以评论'
      })
    },
    onSend(event) {
      //插入数据库
      let content = event.detail.value.content;
      let formId = event.detail.formId;
      if (content.trim() == "") {
        wx.showModal({
          title: '评论内容不能为空！',
        })
        return false;
      }
      wx.showLoading({
        title: '评价中',
        mask: true
      })

      db.collection('blog-comment').add({
        data: {
          content,
          createTime: db.serverDate(),
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then(res => {

        //消息模板 需要使用form表单提交,获取字段使用event.detail.value.content/模板推送使用 event.detail.formId
        wx.cloud.callFunction({
          name: 'sendMessage',
          data: {
            content,
            formId,
            blogId: this.properties.blogId,
          }
        }).then(res => {
          console.log(res)
        })


        wx.hideLoading()
        wx.showToast({
          title: '评论成功！',
        })
        this.setData({
          modalShow: false
        })
        event.detail.value.content = "";
        //抛出评论成功
        this.triggerEvent('refreshCommentList')
      })

    },
    onShare(event) {
      console.log(event)
    }
  }
})